import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

export interface CounterState {
  value: number;
}

const initialState: CounterState = {
  value: 0
}

// MARK: 4、创建一个 store 切片
export const counterSlice = createSlice({
  name: 'counter',
  // 初始值
  initialState,
  // 同步的 actions
  reducers: {
    // MARK: 5、redux-toolkit 使用 immer 库实现不可变数据，我们可以直接修改 state
    increment: state => {
      state.value += 1;
    },
    decrement: state => {
      state.value -=1;
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    }
  }
});

// MARK: 6、导出 actions
export const { increment, decrement, incrementByAmount } = counterSlice.actions

export default counterSlice.reducer
